package pers.llc.css.lock.reentrant;

import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lls
 * @time 2018-10-01
 */
public class MyLock {

    static ExecutorService threadPool = new ThreadPoolExecutor(
                    3,
            100,
            3,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(3),
            new ThreadPoolExecutor.DiscardOldestPolicy());


    public static void init() {
        final OupPrint oupPrint = new OupPrint();
        threadPool.execute(() -> {
            try {
                while (true) {
                    Thread.sleep(1000);
                    oupPrint.out("1--------hadoop");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        threadPool.execute(() -> {
            try {
                while (true) {
                    Thread.sleep(1000);
                    oupPrint.out("2--------spark");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }

    static class OupPrint {
        Lock lock = new ReentrantLock();
        public void out(String str) {
            lock.lock();
            try {
                for (int i = 0; i < str.length(); i++) {
                    System.out.print(str.charAt(i));
                }
                System.out.println();
            } finally {
                //之前释放锁出现异常将不会释放
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        MyLock.init();
    }
}
